#ifndef LOGGER_H
#define LOGGER_H

#include <QString>
#include <QTextStream>
#include <QDateTime>
#include <QFile>

/// \todo just use Wt WLogger
/// log all commands from console and web ui
/// remake architecture!
class Logger : public QObject
{
    Q_OBJECT

    public: bool            isOk;
    ///< If is not Ok - shutdown application :), default - true

    private: QFile          *logFile = nullptr;

    public: bool            copyMsgToUI;

    public: Logger(const bool copyMsgToUi = true)
    {
        isOk = true;
        copyMsgToUI = copyMsgToUi;
        QString _logFileName = "BotLog.log";
        for(int _i=1;QFile::exists(_logFileName);++_i)
        {
            _logFileName = "BotLog" + QString::number(_i) + ".log";
        }
        logFile = new QFile(_logFileName);
        if(!logFile->open(QIODevice::WriteOnly | QIODevice::Text))
        {
            // It still not work, because Bot is not running at Logger construction
            // so just check 'isOk' flag
            Q_EMIT SIGNAL_FatalError("FATAL ERROR: Can't open Log File\n");
            isOk = false;
        }
        else
            SLOT_WriteToLog("Logging is started\n");
    }

    public: ~Logger()
    {
        if(logFile!=nullptr)
        {
            logFile->flush();
            logFile->close();
            delete logFile;
        }
    }

    public: Q_SIGNAL void SIGNAL_WriteUIString(const QString message) const;
    ///< try to chatch it with UI

    public: Q_SIGNAL void SIGNAL_FatalError(QString message) const;
    ///< UI Output, connect to Bot SLOT_FatalError, use to throw exeption and exit application

    /// Slot for writing data to log file.
    public: Q_SLOT void SLOT_WriteToLog(const QString message) const
    {
        QString _str = QTime::currentTime().toString() + " " + message;
        if(copyMsgToUI)
            Q_EMIT SIGNAL_WriteUIString(_str);
        if(logFile)
        {
            QTextStream _qtOut(logFile);
            _qtOut << _str;
        }
    }
};

#endif // LOGGER_H
